﻿using System.Collections;
using System.Linq;

using Castle.MonoRail.Framework;

namespace StateTheater.Component
{
    public class ListByInitialComponent : ViewComponent
    {
        private ICollection elements;

        public override void Initialize()
        {
            base.Initialize();
            elements = (ICollection)ComponentParams["elements"];
   
        }

        public override void Render()
        {
            base.Render();
            char lastInitial = '@';
            bool hasHeader = Context.HasSection("letterheader");
            bool hasFooter = Context.HasSection("letterfooter");

            bool hasAltItem = Context.HasSection("altitem");
            bool hasItem = Context.HasSection("item");
            bool hasUnused = Context.HasSection("unusedletters");

            if (Context.HasSection("header"))
                Context.RenderSection("header");
            int index = 0;
            int letterindex = 0;
            foreach (object item in elements)
            {
                char thisInitial = item.ToString()[0];
                if (thisInitial != lastInitial)
                {
                    if ((hasFooter) && lastInitial != '\0')
                        Context.RenderSection("letterfooter");

                    for (char c = (char)(lastInitial + 1); c < thisInitial; ++c)
                    {
                        PropertyBag["initial"] = c;
                        Context.RenderSection("unusedletters");
                    }
                    lastInitial = thisInitial;

                    PropertyBag["initial"] = thisInitial;
                    if (hasHeader)
                        Context.RenderSection("letterheader");
                    letterindex = 0;
                }

                PropertyBag["index"] = ++index;
                PropertyBag["letterindex"] = ++letterindex;
                PropertyBag["item"] = item;

                if (hasAltItem && (index & 1) == 1)
                {
                    Context.RenderSection("altitem");
                }
                else
                {
                    if (hasItem)
                        Context.RenderSection("item");
                    else
                        Context.RenderBody();
                }

                
            }

            if ((hasFooter) && lastInitial != '@')
                Context.RenderSection("letterfooter");

            if (Context.HasSection("footer"))
                Context.RenderSection("footer");

            CancelView();
        }
        readonly string[] sections = new string[] { "letterheader", "item", "altitem", "letterfooter", "header", "footer", "unusedletters" };
        public override bool SupportsSection(string name)
        {
            return sections.Contains(name);
        }

    }
}
